<?php

namespace App\Admin\Controllers;

use App\Events\WorkshopCreated;
use App\Events\WorkshopUpdated;
use App\model\Area;
use App\model\City;
use App\model\Park;
use App\model\admin\Workshop;


use App\Http\Controllers\Controller;
use App\model\WorkshopContact;
use App\model\WorkshopHangye;
use App\model\WorkshopIndustry;
use App\model\WorkshopPropertyType;
use App\model\WorkshopPurpose;
use App\model\WorkshopTag;
use App\model\WorkshopWeight;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use function foo\func;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\MessageBag;

class WorkshopController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('厂房管理')
            ->description('厂房管理')
            ->body($this->grid());
    }
    /**
     * Update the specified resource in storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {


        return $this->form($id)->update($id);
    }
    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('厂房管理详情')
            ->description('厂房管理详情')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {

        return $content
            ->header('厂房管理编辑')
            ->description('厂房管理编辑')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content, Request $request)
    {

        if (!$request->reflash) {
            return redirect('/admin/workshop/create?reflash=1');
        }
        return $content
            ->header('厂房管理创建')
            ->description('厂房管理创建')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Workshop);

        $grid->id('Id');
        $grid->model()->withoutGlobalScope('shenhe')->orderBy('created_at','desc');
        $grid->title('厂房标题');
       // $grid->rent('租金');
        //$grid->price('单位价格');
        $grid->type('出租/出售类型')->display(function ($value) {
            if ($value == 0) {
                return '出租';
            } else if ($value == 1) {
                return '出售';
            } else {
                return '可租可售';
            }
        });
        //$grid->workshop_property_type_id('物业类型')->display(function ($value) {
         //   return WorkshopPropertyType::find($value)->name ?? '';
       // });
        $grid->area('厂房面积(㎡)');
        // $grid->tag('标签');
         $grid->address('厂房地址');
        //$grid->built_area('建筑面积');
        //$grid->high('首层高度');
        //$grid->floor('楼层数');
        //$grid->elevator('电梯类型');
        //$grid->distribution('配电类型');
      //  $grid->code('厂房编号');
        //$grid->id_hot('推荐');
        $grid->click_count('点击量');
        $grid->call_count('电话拨打次数');
        //$grid->owner('业主名称');
        //$grid->ownertel('业主电话');
        $grid->park_id('园区')->display(function ($value) {
            return Park::find($value)->title ?? '';
        });
      /*  $grid->is_out('来自')->display(function ($value) {
             return   Workshop::$sourceMap[$value];
        });*/

        $grid->column('yulan', '预览')->display(function ($vlaue) {
            return "<a href='" . config('admin.app_outurl') . "/detail/{$this->id}' target='_blank'> 查看</a>";
        });
        $grid->actions(function (Grid\Displayers\Actions $tools){
          //  $tools->disableView();
        });
// 设置text、color、和存储值
        $states = [
            '不推荐', '推荐'
        ];
        $grid->is_recommend('是否推荐')->select($states);
        $states = [
            '下架', '上架'
        ];
        $grid->is_published('是否上架')->select($states);
        $states = [
            '不置顶', '置顶'
        ];
        $grid->is_zhiding('是否置顶')->select($states);

        //$grid->desc('厂房描述');
        $grid->updated_at('更新时间');
        $grid->created_at('创建时间');

        //筛选功能
        $grid->filter(function (Grid\Filter $filter) {
            // 去掉默认的id过滤器
            $filter->column(1 / 2, function (Grid\Filter $filter) {
                $type = [
                    ' ' => '全部',
                    0 => '出租',
                    1 => '出售',
                    2 => '可租可售',
                ];
                $filter->disableIdFilter();
                $filter->equal('is_recommend', '是否推荐')->select([
                    ' ' => '全部',
                    0 => '不推荐',
                    1 => '推荐',
                ]);
                $filter->equal('is_published', '是否上架')->select([
                    ' ' => '全部',
                    0 => '下架',
                    1 => '上架',
                ]);
                $filter->equal('is_zhiding', '是否置顶')->select([
                    ' ' => '全部',
                    0 => '非主推盘',
                    1 => '主推盘',
                ]);

                $filter->equal('p_province_id', '城市')->select(City::getSelectOptions());
                if (\Request::get('p_province_id')) {
                    $filter->equal('p_city_id', '区域')->select(City::getSelectOptions(\Request::get('p_province_id')));
                }
                if (\Request::get('p_city_id')) {
                    $filter->equal('p_district_id', '下级区域')->select(City::getSelectOptions(\Request::get('p_city_id')));
                }
                $filter->like('address','地址');
                $filter->equal('type', '租售类型')->select($type);
                $filter->equal('park_id', '园区')->select(Park::getSelectOptions());
            });

            $filter->column(1 / 2, function ($filter) {
                $filter->like('title', '厂房名称');
                $filter->like('code', '厂房编号');
                $filter->where(function ($query) {
                    $query->whereHas('industry', function ($query) {
                        $query->whereIn('workshop_industry.id', $this->input);
                    });

                }, '类型')->multipleSelect(WorkshopIndustry::getSelectOptions());
                $filter->where(function ($query) {
                    $query->whereHas('purpose', function ($query) {
                        $query->whereIn('workshop_purpose.id', $this->input);
                    });
                }, '用途')->multipleSelect(WorkshopPurpose::getSelectOptions());
                $filter->where(function ($query) {
                    $query->whereHas('hangye', function ($query) {
                        $query->whereIn('workshop_hangye.id', $this->input);
                    });
                }, '行业')->multipleSelect(WorkshopHangye::getSelectOptions());
                $filter->equal('weight_id','承重')->select(WorkshopWeight::getSelectOptions());

                $filter->equal('is_out', '来源')->select(Workshop::$sourceMap);

                $filter->where(function ($query) {
                    $broker = Broker::where('true_mobile','like',$this->input)->first();
                    $brokerId = $broker?$broker->id:"";
                    $query->where('owner',$brokerId);
                }, '经纪人电话');
            });
        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {

        $show = new Show(Workshop::withoutGlobalScope('shenhe')->findOrFail($id));

        $show->id('Id');
        $show->title('厂房标题');


        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id=0)
    {
        $workshop=new Workshop;

        $form = new Form($workshop);
        $type = [
            0 => '出租',
            1 => '出售',
            2 => '可租可售',
        ];

        $form->tab('基础信息',function(Form $form)use ($type,$id){
            $form->text('title', '厂房标题')->rules('required', [
                'required' => '请输入厂房标题'
            ])->help('必填项');
            $form->radio('type', '出租/出售类型')->options($type)->rules('required', [
                'required' => '请选择出租出售类型'
            ]);
            $form->currency('rent', '租金')->symbol("元/㎡")->help('不填写则面议')->options([
                'alias'              => 'integer',
                'prefix'             => '',
                'removeMaskOnSubmit' => false,
            ]);
            $form->currency('price', '出售价格')->symbol("元/㎡")->help('不填写则面议')->options([
                'alias'              => 'integer',
                'prefix'             => '',
                'removeMaskOnSubmit' => false,
            ]);
            $form->radio('is_rent','租赁方式')->options(
                Workshop::$rentMap
            );

         //   $form->number('payratio', '首付比例');
            $form->html(view('admin.status'));//这里是脚本


        //    $form->radio('fuyong', '付佣')->options(Workshop::$fuyongMap);
            $form->radio('status','状态')->options(Workshop::$statusMap)->rules('required', [
                'required' => '请选择状态'
            ]);;

            $form->dateRange('date_of_commission','commission_end_day','委托日期')->help('开始时间结束时间')->rules('required', [
                'required' => '请选择委托日期'
            ]);;
            $form->select('p_province_id', '城市')->options(City::getSelectOptions())->load('p_city_id', '/admin/api/area')->rules('required', [
                'required' => '请选择城市'
            ]);
            $form->select('p_city_id', '区域')->options(function ($id) {
                $id = $id ?: old('p_city_id');
                if($id)
                return City::option($id);
            })->load('p_district_id', '/admin/api/area1')->rules('required', [
                'required' => '请选择区域'
            ]);
            $form->select('p_district_id', '下级区域')->options(function ($id) {
                $id = $id ?: old('p_district_id');
                if($id)
                return City::option($id);
            });
            $form->text('address', '厂房地址')->rules('required', [
                'required' => '请选择厂房地址'
            ]);;
            $form->checkbox('industry', '类型')->options(WorkshopIndustry::getSelectOptions())->rules('required|array|max:2', [
                'required' => '类型',
                'max'=>'类型最多选择2项'
            ]);
            $form->checkbox('purpose', '用途')->options(WorkshopPurpose::getSelectOptions())->rules('required', [
                'required' => '用途'
            ]);
            $form->checkbox('hangye','适用行业')->options(WorkshopHangye::getSelectOptions())->rules('required', [
                'required' => '请选择适用行业'
            ]);
            $form->radio('weight_id','承重')->options(WorkshopWeight::getSelectOptions());
            $form->radio('certificates','证件类型')->options(Workshop::$certificatesMap);
            $form->currency('area', '厂房面积（平方米）')->rules('required', [
                'required' => '请输入厂房面积'
            ])->symbol('平方米')->options([
                'alias'              => 'integer',
                'prefix'             => '',
                'removeMaskOnSubmit' => false,
            ]);

            $form->currency('floor', '厂房所在楼层数')->symbol('层')->options([
                'alias'              => 'integer',
                'prefix'             => '',
                'removeMaskOnSubmit' => false,

            ]);
            $form->currency('high', '层高')->symbol("m")->options([
                'alias'              => 'currency',
                'radixPoint'         => '.',
                'removeMaskOnSubmit' => false,
            ]);
            $form->currency('weight','承重')->symbol('kg')->options([
                'alias'              => 'integer',
                'prefix'             => '',
                'removeMaskOnSubmit' => false,
            ]);
            $form->currency('elevator', '电梯吨位')->symbol("T")->options([
                'alias'              => 'integer',
                'prefix'             => '',
                'removeMaskOnSubmit' => false,
            ]);;
            $form->currency('distribution', '配电类型')->symbol("KW")->options([
                'alias'              => 'integer',
                'prefix'             => '',
                'removeMaskOnSubmit' => false,
            ]);;

            $form->hidden('code', '厂房编号')->default(Carbon::now()->timestamp);
            $form->checkbox('tags', '标签')->options(WorkshopTag::getSelectOptions())->rules('required', [
                'required' => '请输入标签'
            ]);;
            $form->tags('extend_tag', '自定义标签');
            $states = [
                'on' => ['value' => 1, 'text' => '推荐', 'color' => 'success'],
                'off' => ['value' => 0, 'text' => '不推荐', 'color' => 'danger'],
            ];
           $form->uploader('slider','轮播图');
            $form->ckeditor('owndesc', '厂房描述')->help('可输入内容的')->rules('required', [
                'required' => '请输入厂房描述',
            ]);
            $form->ckeditor('inside_desc', '内部描述')->help('可输入内容的');
            $form->switch('is_recommend', '是否推荐')->states($states)->default(1);
            $states = [
                'on' => ['value' => 1, 'text' => '置顶', 'color' => 'success'],
                'off' => ['value' => 0, 'text' => '不置顶', 'color' => 'danger'],
            ];
            $form->switch('is_zhiding', '是否置顶')->states($states)->default(0);
            $states = [
                'on' => ['value' => 1, 'text' => '上架', 'color' => 'success'],
                'off' => ['value' => 0, 'text' => '下架', 'color' => 'danger'],
            ];
            $form->switch('is_published', '是否上架')->states($states)->default(1);

            $is_own = [
                0 => '否',
                1 => '是',
            ];
         //   $form->radio('owner_release', '是否业主发布')->options($is_own);
        })/*->tab('出售信息',function(Form $form){

        })*/->tab('业主信息',function(Form $form)use($id){
            $form->text('owner', '业主名称');
            $form->text('ownertel', '业主电话');
            $form->text('owner_company_name','业主公司名称');
            $form->contact('contact','看盘联系人')->options(compact('id'))/*->rules('required|contact',['required'=>'请填写看盘联系人','contact'=>'请填写看盘联系人'])*/;

        })->tab('园区信息',function(Form $form){
            $form->radio('is_park', '是否园区')->options(Workshop::$parkMap);
            $form->select('park_id', ' 园区')->options(Park::getSelectOptions());
        });
        $form->tools(function (Form\Tools $tools){
            $tools->disableView();
        });

        $form->footer(function (Form\Footer $footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();

            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();

        });
        $form->saving(function ($form)use($id){

            if ($id!=0&&$form->contact){

               $workshopContact= WorkshopContact::whereWorkshopId($id)->get();
                $contact=json_decode($form->contact,true);


                if (count($contact)>0){
                    if ($workshopContact->isNotEmpty()){
                        //先删除
                        $ids=$workshopContact->pluck('id')->toArray();
                        $contactIds=[];
                        $contactAdd=[];
                        foreach ($contact as $item){
                            if (array_key_exists('id',$item)){
                                $contactIds[]=$item['id'];
                                if (in_array($item['id'],$ids)){
                                    $workshopContact=   WorkshopContact::find($item['id']);
                                    $workshopContact->contact_tel=$item['contact_tel'];
                                    $workshopContact->contact_name=$item['contact_name'];
                                    $workshopContact->workshop_id=$id;
                                    $workshopContact->company_name=$item['company_name'];
                                    $workshopContact->isDisabled=$item['isDisabled'];
                                    $workshopContact->save();
                                }
                            }else{
                                $contactAdd[]=$item;
                            }
                        }

                        $ids= array_diff($ids,$contactIds);

                        if (!empty($ids)){
                            WorkshopContact::whereIn('id',$ids)->delete();
                        }

                        if (!empty($contactAdd)){
                            foreach ($contactAdd as $item){
                                $workshopContact=  new WorkshopContact();
                                $workshopContact->contact_tel=$item['contact_tel'];
                                $workshopContact->contact_name=$item['contact_name'];
                                $workshopContact->workshop_id=$id;
                                $workshopContact->company_name=$item['company_name'];
                                $workshopContact->isDisabled=$item['isDisabled'];
                                $workshopContact->save();
                            }
                        }
                    }else{
                        foreach ($contact as $item){
                            $workshopContact=  new WorkshopContact();
                            $workshopContact->contact_tel=$item['contact_tel'];
                            $workshopContact->contact_name=$item['contact_name'];
                            $workshopContact->workshop_id=$id;
                            $workshopContact->company_name=$item['company_name'];
                            $workshopContact->isDisabled=$item['isDisabled'];
                            $workshopContact->save();
                        }

                    }
                }

            }

        });
        $form->saved(function ($form)use ($id){
            if ($id==0&&$form->contact){
                $contact=json_decode($form->contact,true);
                if (count($contact)>0){
                    foreach ($contact as $item){
                        $workshopContact=  new WorkshopContact();
                        $workshopContact->contact_tel=$item['contact_tel'];
                        $workshopContact->contact_name=$item['contact_name'];
                        $workshopContact->workshop_id=$form->model()->id;
                        $workshopContact->company_name=$item['company_name'];
                        $workshopContact->isDisabled=$item['isDisabled'];
                        $workshopContact->save();
                    }
                }else{
                    $error = new MessageBag([
                        'title'   => '请输入联系人信息',
                        'title'   => '请输入联系人信息',
                        'message' => '',
                    ]);
                    return back()->withInput()->with(compact('error'));
                }
                event(new WorkshopCreated($form->model()));

            }else{
                event(new WorkshopUpdated($form->model()));
            }

        });

        return $form;
    }
}
